<template>
    <div class="driver-container">
      <a-card class="driver-card" :bordered="false">
        <!-- 顶部标题和操作区 -->
        <div class="header-section">
          <h2 class="page-title">驾驶员管理</h2>
          <div class="table-operations">
            <a-row :gutter="16" align="middle">
              <a-col :span="8">
                <a-input-search
                  v-model:value="search"
                  placeholder="搜索驾驶员信息..."
                  @search="fetchDriverList"
                  enter-button
                  size="large"
                  class="search-input"
                />
              </a-col>
              <a-col :span="16" style="text-align: right">
                <a-button type="primary" size="large" @click="showAddModal" class="add-button">
                  <user-add-outlined />
                  新增驾驶员
                </a-button>
              </a-col>
            </a-row>
          </div>
        </div>
  
        <!-- 驾驶员表格 -->
        <a-table
          :columns="columns"
          :data-source="driverList"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          class="custom-table"
          :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : '')"
        >
          <!-- 自定义列显示 -->
          <template v-slot:bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'name'">
              <div class="driver-name">
                <user-outlined class="avatar-icon" />
                <span>{{ record.name }}</span>
              </div>
            </template>
            <template v-if="column.dataIndex === 'gender'">
              <a-tag :color="record.gender === 1 ? 'blue' : 'pink'">
                {{ record.gender === 1 ? '男' : '女' }}
              </a-tag>
            </template>
            <template v-if="column.dataIndex === 'departmentId'">
              <a-tag color="green">{{ getDepartmentName(record.departmentId) }}</a-tag>
            </template>
            <template v-if="column.dataIndex === 'phone'">
              <span class="phone-number">{{ record.phone }}</span>
            </template>
            <template v-if="column.dataIndex === 'action'">
              <a-space>
                <a-button type="link" @click="showEditModal(record)" class="edit-button">
                  <edit-outlined />
                  编辑
                </a-button>
                <a-popconfirm
                  title="确定要删除这名驾驶员吗？"
                  @confirm="handleDelete(record.driverId)"
                  ok-text="确定"
                  cancel-text="取消"
                >
                  <a-button type="link" danger class="delete-button">
                    <delete-outlined />
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </a-table>
  
        <!-- 添加/编辑驾驶员模态框 -->
        <a-modal
          :title="modalTitle"
          :open="modalVisible"
          @ok="handleModalOk"
          @cancel="handleModalCancel"
          class="driver-modal"
          :maskClosable="false"
          :width="500"
        >
          <a-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }"
          >
            <a-form-item label="姓名" name="name">
              <a-input 
                v-model:value="formData.name" 
                placeholder="请输入姓名"
                class="custom-input"
              />
            </a-form-item>
            <a-form-item label="性别" name="gender">
              <a-select 
                v-model:value="formData.gender" 
                placeholder="请选择性别"
                class="custom-select"
              >
                <a-select-option :value="1">
                  <man-outlined style="color: #1890ff" /> 男
                </a-select-option>
                <a-select-option :value="2">
                  <woman-outlined style="color: #eb2f96" /> 女
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="年龄" name="age">
              <a-input-number
                v-model:value="formData.age"
                :min="18"
                :max="70"
                placeholder="请输入年龄"
                class="custom-input-number"
                style="width: 100%"
              />
            </a-form-item>
            <a-form-item label="电话" name="phone">
              <a-input 
                v-model:value="formData.phone" 
                placeholder="请输入电话号码"
                class="custom-input"
              />
            </a-form-item>
            <a-form-item label="部门" name="departmentId">
              <a-select 
                v-model:value="formData.departmentId" 
                placeholder="请选择部门"
                show-search
                :filter-option="filterDepartmentOption"
                class="custom-select"
              >
                <a-select-option
                  v-for="dept in getDepartmentList"
                  :key="dept.departmentId"
                  :value="dept.departmentId"
                >
                  {{ dept.departmentName }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="地址" name="address">
              <a-textarea 
                v-model:value="formData.address" 
                placeholder="请输入地址"
                :rows="2"
                class="custom-textarea"
              />
            </a-form-item>
            <a-form-item label="身份证" name="idNumber">
              <a-input 
                v-model:value="formData.idNumber" 
                placeholder="请输入身份证号码"
                class="custom-input"
              />
            </a-form-item>
          </a-form>
        </a-modal>
      </a-card>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { message } from 'ant-design-vue'
  import { 
    PlusOutlined, UserOutlined, UserAddOutlined, EditOutlined, DeleteOutlined,
    ManOutlined, WomanOutlined
  } from '@ant-design/icons-vue'
  import { list,add,del,update } from '@/api/driver'
  import { getDataList } from '@/api/data'
  // 表格列定义
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
    },
    {
      title: '年龄',
      dataIndex: 'age',
      key: 'age',
    },
    {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '部门',
      dataIndex: 'departmentId',
      key: 'departmentId',
    },
    {
      title: '地址',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '身份证',
      dataIndex: 'idNumber',
      key: 'idNumber',
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
    },
  ]
  
  // 数据相关
  const loading = ref(false)
  const driverList = ref([])
  const getDepartmentList=ref([])
  const pagination = ref({
    current: 1,
    pageSize: 10,
    total: 0,
  })
  const search=ref('')
  // 模态框相关
  const modalVisible = ref(false)
  const modalTitle = ref('添加驾驶员')
  const formRef = ref(null)
  const formData = ref({
    name: '',
    gender: '',
    age: '',
    phone: '',
    departmentId: '',
    address: '',
    idNumber: '',
  })
  
  // 表单验证规则
  const rules = {
    name: [
      { required: true, message: '请输入姓名', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    gender: [
      { required: true, message: '请选择性别', trigger: 'change' }
    ],
    age: [
      { required: true, message: '请输入年龄', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入电话号码', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    departmentId: [
      { required: true, message: '请选择部门', trigger: 'change' }
    ],
    address: [
      { required: true, message: '请输入地址', trigger: 'blur' }
    ],
    idNumber: [
      { required: true, message: '请输入身份证号码', trigger: 'blur' },
      { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码', trigger: 'blur' }
    ]
  }
  
  // 获取部门名称
  const getDepartmentName = (departmentId) => {
    const department = getDepartmentList.value.find(dept => dept.departmentId === departmentId)
    return department ? department.departmentName : '-'
  }
  const DataList=async()=>{
        const res =await getDataList();
        console.log(res)
        if(res.code===200){
            getDepartmentList.value=res.data.departmentInfoList
        }
  }
  // 获取驾驶员列表
  const fetchDriverList = async () => {
    loading.value = true
    try {
      const res = await list({
        pageNum: pagination.value.current,
        pageSize: pagination.value.pageSize,
        search: search.value
      })
      driverList.value = res.data.records
      pagination.value.total = res.data.total
    } catch (error) {
      message.error('获取驾驶员列表失败')
    } finally {
      loading.value = false
    }
  }
  
  // 表格分页变化
  const handleTableChange = (pag) => {
    pagination.value.current = pag.current
    pagination.value.pageSize = pag.pageSize
    fetchDriverList()
  }
  
  // 显示添加模态框
  const showAddModal = () => {
    modalTitle.value = '添加驾驶员'
    formData.value = {
      name: '',
      gender: '',
      age: '',
      phone: '',
      departmentId: '',
      address: '',
      idNumber: '',
    }
    modalVisible.value = true
  }
  
  // 显示编辑模态框
  const showEditModal = (record) => {
    modalTitle.value = '编辑驾驶员'
    formData.value = {...record}
    modalVisible.value = true
  }
  
  // 处理模态框确认
  const handleModalOk = () => {
    formRef.value?.validate().then(async () => {
      try {
     
        const res = formData.value.driverId 
          ? await update(formData.value)
          : await add(formData.value)
            console.log(res)
        if(res.code === 200) {
          message.success(`${modalTitle.value}成功`)
          modalVisible.value = false
          fetchDriverList()
        }
      } catch (error) {
        message.error(`${modalTitle.value}失败`)
      }
    })
  }
  
  // 处理模态框取消
  const handleModalCancel = () => {
    modalVisible.value = false
    formRef.value?.resetFields()
  }
  
  // 处理删除驾驶员
  const handleDelete = async (driverId) => {
    try {
      const res = await del(driverId)
      if(res.code === 200) {
        message.success('删除成功')
        fetchDriverList()
      }
    } catch (error) {
      message.error('删除失败')
    }
  }
  
  // 添加部门筛选方法
  const filterDepartmentOption = (input, option) => {
    return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
  }
  
  // 页面加载时获取列表数据
  onMounted(() => {
    fetchDriverList()
    DataList()
  })
  </script>
  
  <style scoped>
  .driver-container {
    padding: 24px;
    background-color: #f0f2f5;
    min-height: 100vh;
  }
  
  .driver-card {
    border-radius: 8px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
  }
  
  .header-section {
    margin-bottom: 24px;
  }
  
  .page-title {
    font-size: 24px;
    color: #1f1f1f;
    margin-bottom: 24px;
    font-weight: 500;
  }
  
  .search-input {
    width: 100%;
    :deep(.ant-input) {
      border-radius: 4px;
    }
  }
  
  .add-button {
    border-radius: 4px;
    height: 40px;
    font-weight: 500;
    box-shadow: 0 2px 0 rgba(0, 0, 0, 0.045);
  }
  
  .custom-table {
    :deep(.ant-table-thead > tr > th) {
      background: #fafafa;
      font-weight: 500;
    }
    
    :deep(.table-striped) {
      background-color: #fafafa;
    }
  }
  
  .driver-name {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .avatar-icon {
      color: #1890ff;
      background: #e6f7ff;
      padding: 4px;
      border-radius: 50%;
    }
  }
  
  .phone-number {
    font-family: 'Roboto Mono', monospace;
    color: #666;
  }
  
  .edit-button {
    color: #1890ff;
  }
  
  .delete-button {
    color: #ff4d4f;
  }
  
  .driver-modal {
    :deep(.ant-modal-header) {
      border-bottom: 1px solid #f0f0f0;
      padding: 16px 24px;
    }
    
    :deep(.ant-modal-footer) {
      border-top: 1px solid #f0f0f0;
      padding: 16px 24px;
    }
  }
  
  .custom-input,
  .custom-select,
  .custom-input-number,
  .custom-textarea {
    width: 100%;
    :deep(.ant-input),
    :deep(.ant-select-selector),
    :deep(.ant-input-number),
    :deep(.ant-input-textarea) {
      border-radius: 4px;
    }
  }
  
  /* 添加动画效果 */
  .add-button,
  .edit-button,
  .delete-button {
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-1px);
    }
  }
  
  /* 响应式调整 */
  @media (max-width: 768px) {
    .driver-container {
      padding: 12px;
    }
    
    .page-title {
      font-size: 20px;
    }
    
    .header-section {
      margin-bottom: 16px;
    }
    
    .search-input,
    .add-button {
      margin-bottom: 12px;
    }
  }
  </style>